#include "translation.h"
#include <stdio.h>
#include "symtable.h"
#include <stdlib.h>
#include <string.h>

void translate(struct ast_node *node) {

	// Output file for worlds
	FILE *f = fopen("worlds.js", "w");

	// Print fixed text
	fprintf(f, "let world_list = [");

	// Print all worlds
	for (int i = 0; i < node->children.elements; i++) {
		struct ast_node *child = dd_da_get(&node->children, i);
		if (i != 0) fprintf(f, ",");
		fprintf(f, "%s", symtable[child->value].lexptr);
	}

	// Print suffix
	fprintf(f, "];");

	// Close file
	fclose(f);

	/* For each world, create a separate file with the world's details
	 */
	for (int i = 0; i < node->children.elements; i++) {

		// Current world
		struct ast_node *world = dd_da_get(&node->children, i);
		struct entry *world_entry = &symtable[world->value];

		// Create a file with name "<worldname>.js" where <worldname> is replaced with the world's name
		char *filename = malloc(sizeof(char) *(strlen(world_entry->lexptr) +3));
		strcpy(filename, world_entry->lexptr);
		strcat(filename, ".js");

		// Open world file for writing
		FILE *f = fopen(filename, "w");

		fprintf(f, "class %s extends World {\n", world_entry->lexptr);
		// ... contents ...
		fprintf(f, "}\n");

		fclose(f);
	}


}
